/*
 * Copyright 2014 Red Hat, Inc.
 *
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  and Apache License v2.0 which accompanies this distribution.
 *
 *  The Eclipse Public License is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 *
 *  The Apache License v2.0 is available at
 *  http://www.opensource.org/licenses/apache2.0.php
 *
 *  You may elect to redistribute this code under either of these licenses.
 */

package com.motu.vertx.module.utility.webtool;

import com.motu.vertx.module.utility.mysql.MysqlTool;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.http.HttpServerResponse;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.ext.auth.jdbc.JDBCAuth;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import io.vertx.ext.web.client.WebClient;
import io.vertx.ext.web.client.WebClientOptions;
import io.vertx.sqlclient.Pool;
import io.vertx.redis.client.RedisAPI;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 * @author <a href="http://tfox.org">Tim Fox</a>
 */
public class QywxLoginHandler extends BaseWebHandler/*implements FormLoginHandler*/ {

	private static final Logger logger = LoggerFactory.getLogger(QywxLoginHandler.class);

	public static JDBCAuth authProvider;
	public static Pool jdbcClientWeb;
	public static RedisAPI redisClient;
	public static WebClient client ;
	
	public static void init(JDBCAuth authProvider, Pool jdbcClientWeb, RedisAPI redisClient, Vertx vertx){
		QywxLoginHandler.authProvider = authProvider;
		QywxLoginHandler.jdbcClientWeb = jdbcClientWeb;
		QywxLoginHandler.redisClient = redisClient;
		QywxLoginHandler.client = WebClient.create(vertx, new WebClientOptions().setKeepAlive(true));
	}

//	@Override
	public static void handle(RoutingContext context) {
		HttpServerRequest req = context.request();
		HttpServerResponse response = context.response();
		JsonObject json = context.body().asJsonObject();
		String ticket = json.getString("ticket");;
		String url = "https://m2oa.m2time.net/sso/serviceValidate?json=1&ticket="+ticket;
		client
		  .getAbs(url)
		  .send(ticketHandle -> {
		    	JsonObject ticketResult = ticketHandle.result().body().toJsonObject();
		    	String qywx_userid = ticketResult.getString("userName");
				Session session = context.session();
				String sql = "select id,username,gmname,password,password_salt,webperms,bigames,depid,groupid,employeeid,relation,gameperms,platform,channel,account_type,enable,feishu_info from manager_users where sso_userid = ?;";
				JsonArray params = new JsonArray().add(qywx_userid);
				MysqlTool.queryJsonArrayFromDb(jdbcClientWeb, sql,params , res->{
					if (res.succeeded()) {
						JsonArray resArray = res.result();
						logger.info(" sql :" + sql + " params:" + params + " resArray: " + resArray);
						if(resArray==null||resArray.isEmpty()) {
							sendHttpResponseError(response, "内部帐号不存在");
							return;
						} else if(resArray.getJsonObject(0).getInteger("enable") == 0) {
							sendHttpResponseError(response, "该用户被禁止登录，请联系管理员！");
							return;
						}else if (resArray.getJsonObject(0).getInteger("account_type") == 2) {
							sendHttpResponseError(response, "请使用账号密码登录");
							return;
						}
						String username = resArray.getJsonObject(0).getString("username");
						loginCallback(context,jdbcClientWeb,redisClient,username,resArray);
					} else {
						sendHttpResponseError(response, res.cause().getMessage());
					}
				}); 
		  		    
		  });
	}
}
